import {
  ActionType,
  ModalForm,
  PageContainer,
  ProCard,
  ProColumns,
  ProForm,
  ProFormDateTimePicker,
  ProFormDigit,
  ProFormMoney,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
  ProTable
} from "@ant-design/pro-components";
import MapContainer from "@/components/AMap/MapContainer";
import React, {useRef, useState} from "react";
import {AutoComplete, Button, Form, message, Modal, Popconfirm, Tooltip} from "antd";
import {history} from '@umijs/max';
import {
  dictList,
  globalApi,
  globalLoadTableApi,
  handleGloblApi,
  handleGloblApiResult
} from "@/services/admin-api/globalApi";
import {citySelect} from "@/pages/Worker/Management";
import dayjs from "dayjs";
import {CloseOutlined, PlusOutlined, SettingFilled} from "@ant-design/icons";
import {ProductInventoryRecord} from "@/pages/Inventory/Record";

let timer: any

const storeSelect = await globalApi('/store/select', {})

type OrderDiscounts = {
  discountsId: number
  orderId: number
  beforeTotalPrice: number
  discountsMoney: number
  discountsType: number
  afterTotalPrice: number
  discountsRemark: string
  delFlag: boolean
  createTime: string
  createUserId: number
  createUserName: string
  updateTime: string
  updateUserId: number
  updateUserName: string
}

export const discountsType = await dictList('discounts_type')

export default () => {

  const actionRef = useRef<ActionType>()
  const actionDiscountsRef = useRef<ActionType>()
  const mapRef = useRef<any>()
  const [form] = Form.useForm();
  const [formProductSave] = Form.useForm();
  const [formDiscountsSave] = Form.useForm();
  const [startAddressList, setStartAddressList] = useState([])
  const [newAddressList, setNewAddressList] = useState([])
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isDiscountsPriceModalOpen, setIsDiscountsPriceModalOpen] = useState(false)
  const [isProductSaveModalOpen, setProductSaveIsModalOpen] = useState(false)
  const [isDiscountsSaveModalOpen, setDiscountsSaveIsModalOpen] = useState(false)
  const [isOtherPrice, setIsOtherPrice] = useState<boolean>(false)

  const aMapDriving = () => {
    const value = form.getFieldsValue()
    console.log('value = ', value)
    if (value.startAddressLat && value.startAddressLng && value.newAddressLat && value.newAddressLng) {
      mapRef.current?.clearMarker()
      const startLngLat = [value.startAddressLng, value.startAddressLat] // 起始点坐标
      const endLngLat = [value.newAddressLng, value.newAddressLat] // 终点坐标
      let driving = mapRef.current?.driving()
      driving.search(startLngLat, endLngLat, function (status: any, result: any) {
        if (status === "complete") {
          // status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
          // 查询成功时，result 即为对应的驾车导航信息
          console.log(result);

          form.setFieldsValue({
            distance: (result.routes[0].distance / 1000).toFixed(2)
          })

        } else {
          console.log("获取驾车数据失败：" + result);
        }
      });
    }
  }

  const loadInitData = async () => {
    const urlParams = new URL(window.location.href).searchParams;
    const orderId = urlParams.get('orderId');
    console.log('urlParams = ', urlParams, ', orderId = ', orderId)

    if (orderId) {
      const hide = message.loading('正在加载数据');
      const result = await globalApi('/order/detail', {orderId})
      console.log('result = ', result)
      const orderTmp = {...result.data}
      form.setFieldsValue({
        ...orderTmp,
        productList: orderTmp.productDetailsStr,
      })

      if (orderTmp.serviceTime) {
        form.setFieldsValue({serviceTime: dayjs(orderTmp.serviceTime),})
      }

      if (orderTmp.storeName) {
        form.setFieldsValue({store: {label: orderTmp.storeName, value: orderTmp.storeId},})
      }

      if (orderTmp.cityName) {
        form.setFieldsValue({city: {label: orderTmp.cityName, value: orderTmp.cityCode},})
      }


      // form.setFieldsValue({orderId: result.data.orderId, customerPhone: result.data.customerPhone,})
      aMapDriving()
      // setTimeout(aMapDriving, 1500)
      hide();
      message.success('Loading successfully');
    }

  }

  const productListColumns: ProColumns<ProductInventoryRecord>[] = [
    // {title: '', valueType: 'indexBorder', width: 30},
    {title: '记录ID', dataIndex: 'productInventoryRecordId', valueType: 'digit'},
    {title: '产品名称', dataIndex: 'productName', valueType: 'text'},
    {title: '产品规格', dataIndex: 'productSpecification', valueType: 'text'},
    {title: '单价', dataIndex: 'productPrice', valueType: 'money'},
    {title: '数量', dataIndex: 'changeInventory', valueType: 'digit'},
    {title: '总价', dataIndex: 'productTotalPrice', valueType: 'money', hideInSearch: true},
    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
    {
      title: <SettingFilled/>,
      render: (_, record) => [
        <Tooltip key={'delrecord_' + record.productInventoryRecordId} title="删除">
          <Popconfirm
            title="删除增值服务"
            description="确认删除这条增值服务？"
            onConfirm={async () => {

              const r = await handleGloblApiResult('/order/productRemove', {productInventoryRecordId: record.productInventoryRecordId})
              form.setFieldsValue({
                productTotalPrice: r.data.productTotalPrice,
                totalPrice: r.data.totalPrice,
                productName: r.data.productName,
              })
              actionRef.current?.reload()

              // const result = await orderDetail({orderId: form.getFieldValue('orderId')})
              const result = await globalApi('/order/detail', {orderId: form.getFieldValue('orderId')})
              console.log('result = ', result)
              const orderTmp = {...result.data}
              form.setFieldsValue({
                productList: orderTmp.productDetailsStr,
              })

              // await handleGloblApi('/order/productRemove', {productInventoryRecordId: record.productInventoryRecordId})
              // actionRef.current?.reload()
            }}
            onCancel={() => {
            }}
            okText="Yes"
            cancelText="No"
          >
            <Button size="small" icon={<CloseOutlined/>} type="primary" danger/>
          </Popconfirm>
        </Tooltip>,
      ],
      valueType: 'option',
    },
  ];

  const discountsListColumns: ProColumns<OrderDiscounts>[] = [
    // {title: '', valueType: 'indexBorder', width: 30},
    {title: '记录ID', dataIndex: 'discountsId', valueType: 'digit'},
    {title: '订单ID', dataIndex: 'orderId', valueType: 'text'},
    {
      title: '优惠类型',
      dataIndex: 'discountsType',
      valueType: 'select',
      fieldProps: {options: discountsType.data}
    },
    {title: '优惠前价格', dataIndex: 'beforeTotalPrice', valueType: 'money'},
    {title: '优惠金额', dataIndex: 'discountsMoney', valueType: 'money'},
    {title: '优惠后价格', dataIndex: 'afterTotalPrice', valueType: 'money'},
    {title: '备注', dataIndex: 'discountsRemark', valueType: 'text'},
    {title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '创建用户ID', dataIndex: 'createUserId', valueType: 'digit', hideInSearch: true,},
    {title: '创建用户', dataIndex: 'createUserName', valueType: 'text', hideInSearch: true,},
    {title: '更新时间', dataIndex: 'updateTime', valueType: 'dateTime', hideInSearch: true,},
    {title: '更新用户ID', dataIndex: 'updateUserId', valueType: 'digit', hideInSearch: true,},
    {title: '更新用户', dataIndex: 'updateUserName', valueType: 'text', hideInSearch: true,},
  ]

  const calculatePrice = () => {
    const r = form.getFieldsValue(['startFloorPrice', 'newFloorPrice', 'kmPrice', 'productTotalPrice', 'otherPrice', 'discountsPrice'])
    console.log('calculatePrice r = ', r)
    let startFloorPrice = r.startFloorPrice ? r.startFloorPrice : 0;
    let newFloorPrice = r.newFloorPrice ? r.newFloorPrice : 0;
    let kmPrice = r.kmPrice ? r.kmPrice : 0;
    let productTotalPrice = r.productTotalPrice ? r.productTotalPrice : 0;
    let otherPrice = r.otherPrice ? r.otherPrice : 0;
    let discountsPrice = r.discountsPrice ? r.discountsPrice : 0;
    // let totalPrice = r.totalPrice ? r.totalPrice : 0;

    form.setFieldsValue({
      totalPrice: startFloorPrice + newFloorPrice + kmPrice + productTotalPrice + otherPrice - discountsPrice
    })
  }

  return <PageContainer header={{title: '', breadcrumb: {},}}>
    <ProCard>
      <ProForm
        form={form} autoFocusFirstInput onFinish={async (value) => {
        console.log('value = ', value);
        let success = await handleGloblApi('/order/saveOrUpdate', value)
        if (success) {
          history.back()
        }
      }}>
        <ProFormDigit name="orderId" hidden/>
        <ProForm.Item>
          <MapContainer ref={mapRef} init={async () => {
            // aMapDriving()
            await loadInitData()
          }}/>
        </ProForm.Item>
        <ProForm.Group>
          <ProForm.Item label="起点地址" name="startAddress">
            <AutoComplete
              style={{width: 328}} options={startAddressList} placeholder={"请输入"}
              onSelect={(data: string) => {
                console.log('onSelect', data);
                startAddressList.forEach((e: any, i) => {
                  if (e.label === data) {
                    console.log(`select e = ${e}`, e)
                    // console.log('dis = ', (e.routes[0].distance / 1000).toFixed(2))
                    form.setFieldsValue({
                      startAddressLat: e.location.lat,
                      startAddressLng: e.location.lng,
                      // distance: (e.routes[0].distance / 1000).toFixed(2)
                    })
                    mapRef.current?.addMarker(e.location)
                    return false
                  }
                })

                console.log('form = ', form.getFieldsValue())

                aMapDriving()
              }}
              onSearch={(value) => {
                console.log('search value = ', value)

                if (timer) {
                  clearTimeout(timer)
                  timer = null
                }

                timer = setTimeout(() => {
                  let autoComplete = mapRef.current?.autoComplete()
                  console.log(`autoComplete ${autoComplete}`)
                  autoComplete.search(value, function (status: any, result: any) {
                    console.log(`status = ${status}, result = ${result}`)
                    if (status === 'complete') {
                      // 搜索成功时，result 即是对应的匹配数据
                      result.tips.forEach((e: any, i: any) => {
                        e.label = e.district + e.name
                        e.value = e.label
                      })
                      console.log('result = ', result);
                      // return result.tips
                      setStartAddressList(result.tips)
                    }
                  });
                }, 500)
              }}
            />
          </ProForm.Item>
          <ProFormDigit width={"xs"} min={Number.MIN_SAFE_INTEGER} name="startFloor" label="起点楼层"/>
          <ProFormSwitch
            name="startElevator" fieldProps={{checkedChildren: '有', unCheckedChildren: '无'}}
            label="起点电梯" initialValue={false}/>
          <ProFormDigit name="startAddressLat" label="startAddressLat" hidden/>
          <ProFormDigit name="startAddressLng" label="startAddressLng" hidden/>
          <ProForm.Item label="新家地址" name="newAddress">
            <AutoComplete
              placeholder={"请输入"} style={{width: 328}} options={newAddressList}
              onSelect={(data: string) => {
                console.log('onSelect', data)
                newAddressList.forEach((e: any, i) => {
                  if (e.label === data) {
                    console.log(`select e = ${e}`, e)
                    form.setFieldsValue({newAddressLat: e.location.lat, newAddressLng: e.location.lng})
                    mapRef.current?.addMarker(e.location)
                    return false
                  }
                })
                aMapDriving()
              }}
              onSearch={(value) => {
                console.log('search value = ', value)

                if (timer) {
                  clearTimeout(timer)
                  timer = null
                }

                timer = setTimeout(() => {
                  let autoComplete = mapRef.current?.autoComplete()
                  console.log(`autoComplete ${autoComplete}`)
                  autoComplete.search(value, function (status: any, result: any) {
                    console.log(`status = ${status}, result = ${result}`)
                    if (status === 'complete') {
                      // 搜索成功时，result 即是对应的匹配数据
                      result.tips.forEach((e: any, i: any) => {
                        e.label = e.district + e.name
                        e.value = e.label
                      })
                      console.log('result = ', result);
                      // return result.tips
                      setNewAddressList(result.tips)
                    }
                  });
                }, 500)
              }}
            />
          </ProForm.Item>
          <ProFormDigit name="newAddressLat" label="newAddressLat" hidden/>
          <ProFormDigit name="newAddressLng" label="newAddressLng" hidden/>
          <ProFormDigit width={"xs"} name="newFloor" min={Number.MIN_SAFE_INTEGER} label="新家楼层"/>
          <ProFormSwitch
            name="newElevator" fieldProps={{checkedChildren: '有', unCheckedChildren: '无'}} label="新家电梯"
            initialValue={false}/>
          <ProFormDigit width={"xs"} name="distance" label="距离（km）"/>
        </ProForm.Group>
        <ProForm.Group>
          <ProFormText name="customerName" label="客户名称" fieldProps={{autoComplete: 'new-password'}}/>
          <ProFormText
            name="customerPhone" label="客户电话" fieldProps={{autoComplete: 'new-password'}}
            rules={[{required: true}, {pattern: /^1\d{10}$/, message: '请输入正确格式手机号'}]}/>
          <ProFormDateTimePicker
            name="serviceTime" label="服务时间" transform={(value) => {
            console.log('value = ', value)
            if (typeof value === 'string') {
              return {serviceTimeStr: value}
            }
            return {serviceTimeStr: value.format('YYYY-MM-DD HH:mm:ss')}
          }}/>
          <ProFormDigit name="storeId" hidden/>
          <ProFormText name="storeName" hidden/>

          <ProFormText name="cityCode" hidden/>
          <ProFormText name="cityName" hidden/>

          <ProFormSelect
            name={"city"} label={"城市"} showSearch options={citySelect.data} fieldProps={{
            labelInValue: true,
          }} transform={(val) => {
            return {cityCode: val.value, cityName: val.label}
          }}/>
          <ProFormSelect
            name={"store"} tooltip={"先选城市"} label={"店铺"} showSearch options={storeSelect.data}
            dependencies={['city']}
            request={async (param) => {
              if (param.cityCode) {
                const r = await globalApi('/store/select', param)
                return r.data
              }
              return []
            }}
            // transform={(val) => {
            //   return {storeId: val.value, storeName: val.label}
            // }}
            fieldProps={{
              labelInValue: true, onSelect: (val) => {
                form.setFieldsValue({storeId: val.value, storeName: val.label})
              }
            }}/>

          <ProFormText
            tooltip={"请通过服务内容选择第一个主显的套餐"} name="productName" label="套餐" disabled/>

        </ProForm.Group>
        <ProForm.Group>
          <ProFormTextArea width={"lg"} label={"服务内容"} fieldProps={{
            onClick: () => {
              const store = form.getFieldValue("store")
              console.log('storeId = ', store)
              if (store) {
                const orderId = form.getFieldValue("orderId")
                if (orderId) {
                  setIsModalOpen(true)
                } else {
                  message.error('订单需保存后编辑才能添加服务')
                }
              } else {
                message.warning("请先选择店铺")
              }
            }
          }} name="productList" tooltip={"服务内容添加的第一个主显套餐就是此订单的套餐"}/>
          <ProFormTextArea
            label={"客户留言"} name="customerRemark" tooltip={"客户下单时备注"}/>
          <ProFormTextArea label={"服务备注"} name="serviceRemark" tooltip={"给工作人员看"}/>
          <ProFormTextArea label={"订单备注"} name="orderRemark" tooltip={"给其他操作系统的工作人员看"}/>
        </ProForm.Group>
        <ProForm.Group>
          <ProFormMoney width={"xs"} name="startFloorPrice" label="起点楼层费" fieldProps={{
            onChange: calculatePrice
          }}/>
          <ProFormMoney width={"xs"} name="newFloorPrice" label="新家楼层费" fieldProps={{
            onChange: calculatePrice
          }}/>
          <ProFormMoney width={"xs"} name="kmPrice" label="公里费" fieldProps={{
            onChange: calculatePrice
          }}/>
          <ProFormMoney width={"xs"} name="productTotalPrice" label="服务总价" disabled/>
          <ProFormMoney
            width={"xs"} name="otherPrice"
            tooltip={"其他费用与优惠费用只能通过添加优惠或添加其他费用修改，请不要手动修改此项"}
            label="其他费用" fieldProps={{
            onClick: () => {
              const orderId = form.getFieldValue("orderId")
              if (orderId) {
                setIsOtherPrice(true)
                setIsDiscountsPriceModalOpen(true)
              } else {
                message.error('订单需保存后编辑才能添加其他费用')
              }
            }
          }}/>
          <ProFormMoney
            width={"xs"} fieldProps={{
            onClick: () => {
              const orderId = form.getFieldValue("orderId")
              if (orderId) {
                setIsOtherPrice(false)
                setIsDiscountsPriceModalOpen(true)
              } else {
                message.error('订单需保存后编辑才能添加优惠金额')
              }
            }
          }} tooltip={"其他费用与优惠费用只能通过添加优惠或添加其他费用修改，请不要手动修改此项"} name="discountsPrice"
            label="优惠金额"/>

          <ProFormMoney width={"xs"} name="totalPrice" label="总价" disabled/>
          <ProFormMoney width={"xs"} name="shouldDeposit" label="应付定金"/>
          <ProFormMoney width={"xs"} name="payDeposit" label="实付定金" disabled/>
          <ProFormMoney width={"xs"} name="payFinalPayment" label="实付尾款" disabled/>
        </ProForm.Group>
      </ProForm>
    </ProCard>

    <Modal width={1200} destroyOnClose open={isModalOpen} onOk={() => {
      setIsModalOpen(false)
    }} onCancel={() => {
      setIsModalOpen(false)
    }}>
      <ProTable
        headerTitle={
          <Tooltip title={"新增服务"}>
            <Button
              key="primary" type="primary" icon={<PlusOutlined/>} onClick={() => {
              const store = form.getFieldValue('store')
              const orderId = form.getFieldValue('orderId')
              console.log('store = ', store)
              formProductSave.setFieldsValue({storeId: store.value, storeName: store.label, orderId})
              setProductSaveIsModalOpen(true)
            }}/></Tooltip>
        }
        search={false} columns={productListColumns} size={"small"} actionRef={actionRef}
        request={async (param) => globalLoadTableApi('/order/productTable', {
          ...param,
          orderId: form.getFieldValue('orderId')
        })}
        rowKey={(record) => record.orderId}
        columnsState={{
          defaultValue: {
            delFlag: {show: false},
            createUserId: {show: false},
            updateUserId: {show: false}
          }
        }}/>
    </Modal>

    <Modal width={1200} destroyOnClose open={isDiscountsPriceModalOpen} onOk={() => {
      setIsDiscountsPriceModalOpen(false)
    }} onCancel={() => {
      setIsDiscountsPriceModalOpen(false)
    }}>
      <ProTable
        headerTitle={
          <Tooltip title={isOtherPrice ? '新增其他费用' : "新增优惠"}>
            <Button
              key="primary" type="primary" icon={<PlusOutlined/>} onClick={() => {
              formDiscountsSave.setFieldsValue({orderId: form.getFieldValue("orderId")})
              setDiscountsSaveIsModalOpen(true)
            }}/></Tooltip>
        }
        search={false} columns={discountsListColumns} size={"small"} actionRef={actionDiscountsRef}
        request={async (param) => globalLoadTableApi('/order/discountsTable', {
          ...param,
          orderId: form.getFieldValue('orderId'),
          otherPrice: isOtherPrice,
        })}
        rowKey={(record) => record.discountsId}
        columnsState={{
          defaultValue: {
            delFlag: {show: false},
            createUserId: {show: false},
            updateUserId: {show: false}
          }
        }}/>
    </Modal>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="400px" open={isProductSaveModalOpen} onOpenChange={setProductSaveIsModalOpen} form={formProductSave}
      onFinish={async (value) => {
        console.log('value = ', value)
        const r = await handleGloblApiResult('/order/productSave', value)

        if (r.success) {

          form.setFieldsValue({
            productTotalPrice: r.data.productTotalPrice,
            totalPrice: r.data.totalPrice,
            productName: r.data.productName,
          })
          actionRef.current?.reload()

          // const result = await orderDetail({orderId: value.orderId})
          const result = await globalApi('/order/detail', {orderId: value.orderId})
          console.log('result = ', result)
          const orderTmp = {...result.data}
          form.setFieldsValue({
            productList: orderTmp.productDetailsStr,
          })

          return true
        }

        return false
      }}
    >
      <ProFormDigit name={"orderId"} hidden/>

      <ProFormDigit name={"productId"} hidden/>
      <ProFormText name={"productName"} hidden/>

      <ProFormDigit name={"storeId"} hidden/>
      <ProFormText name={"storeName"} hidden/>
      <ProFormSelect label="产品" name="product" rules={[{required: true}]} showSearch request={async (param) => {
        console.log('param = ', param)
        const r = await globalApi('/order/productSelect', param)
        return r.data
      }} fieldProps={{
        labelInValue: true, onSelect: (val) => {
          formProductSave.setFieldsValue({productId: val.value, productName: val.label})
        }
      }}/>
      <ProFormDigit name={"productSpecificationId"} hidden/>
      <ProFormText name={"productSpecification"} hidden/>
      <ProFormSelect
        dependencies={['productId']} label="规格" name="specification" rules={[{required: true}]}
        request={async (param) => {
          console.log('param = ', param)
          const r = await globalApi('/order/productSpecificationsSelect', param)
          // setProductSpecificationList(r.data)
          return r.data
        }} fieldProps={{
        labelInValue: true, onSelect: (val) => {
          console.log('specification val = ', val)
          formProductSave.setFieldsValue({
            productSpecificationId: val.value,
            productSpecification: val.label,
          })
        }
      }}/>
      <ProFormDigit label={"数量"} rules={[{required: true}]} name={"changeInventory"}/>
    </ModalForm>

    <ModalForm
      modalProps={{destroyOnClose: true}} autoFocusFirstInput submitTimeout={15000}
      width="400px" open={isDiscountsSaveModalOpen} onOpenChange={setDiscountsSaveIsModalOpen} form={formDiscountsSave}
      onFinish={async (value) => {
        console.log('value = ', value)
        const r = await handleGloblApiResult('/order/discountsSave', value)
        form.setFieldsValue({
          discountsPrice: r.data.discountsPrice,
          totalPrice: r.data.totalPrice,
          otherPrice: r.data.otherPrice,
        })
        actionDiscountsRef.current?.reload()
        return true
      }}
    >
      <ProFormDigit name={"orderId"} hidden/>
      {isOtherPrice ? <ProFormDigit name={"discountsType"} initialValue={0} hidden/> : <ProFormSelect
        name={"discountsType"} rules={[{required: true}]} label={"类型"} options={[{label: '客服优惠', value: 1}]}/>}

      <ProFormMoney name={"discountsMoney"} rules={[{required: true}]} label={"金额"}/>
      <ProFormText name={"discountsRemark"} rules={[{required: true}]} label={"备注"}/>
    </ModalForm>

  </PageContainer>
}
